/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */

package cc.iotkit.data.service;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.dao.MapFenceDevicesRepository;
import cc.iotkit.data.manager.IMapFenceDevicesData;
import cc.iotkit.data.model.TbMapFenceDevices;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.map.MapFenceDevices;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static cc.iotkit.data.model.QTbDeviceInfo.tbDeviceInfo;
import static cc.iotkit.data.model.QTbMapFenceDevices.tbMapFenceDevices;
import static cc.iotkit.data.model.QTbProduct.tbProduct;

@Primary
@Service
public class MapFenceDevicesDataImpl implements IMapFenceDevicesData, IJPACommData<MapFenceDevices, Long> {
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private MapFenceDevicesRepository MapFenceDevicesRepository;

    @Override
    public JpaRepository getBaseRepository() {
        return MapFenceDevicesRepository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbMapFenceDevices.class;
    }

    @Override
    public Class getTClass() {
        return MapFenceDevices.class;
    }



    @Override
    public MapFenceDevices findById(Long s) {
        return MapstructUtils.convert(MapFenceDevicesRepository.findById(s).orElse(null), MapFenceDevices.class);
    }

    @Override
    public MapFenceDevices save(MapFenceDevices data) {
        if (data.getId()==null||data.getId().equals(0L)) {
            data.setTenantId(Long.valueOf(LoginHelper.getTenantId()));
            data.setUid(LoginHelper.getUserId());
            data.setCreateAt(System.currentTimeMillis());
            data.setCreateBy(LoginHelper.getUserId());
            data.setCreateDept(LoginHelper.getDeptId());
        }else{
            data.setUpdateAt(System.currentTimeMillis());
            data.setUpdateBy(LoginHelper.getUserId());
        }
        MapFenceDevicesRepository.save(MapstructUtils.convert(data, TbMapFenceDevices.class));
        return data;
    }

    @Transactional
    public List<MapFenceDevices> saveAll(List<MapFenceDevices> datas) {
        for(MapFenceDevices data : datas){
            if (data.getId()==null||data.getId().equals(0L)) {
                data.setTenantId(Long.parseLong(LoginHelper.getTenantId()));
                data.setCreateDept(LoginHelper.getDeptId());
                data.setUid(LoginHelper.getUserId());
                data.setCreateAt(System.currentTimeMillis());
                data.setCreateBy(LoginHelper.getUserId());
            }else{
                data.setUpdateAt(System.currentTimeMillis());
                data.setUpdateBy(LoginHelper.getUserId());
            }
        }

        List<TbMapFenceDevices> results= MapFenceDevicesRepository.saveAll(MapstructUtils.convert(datas, TbMapFenceDevices.class));
        return MapstructUtils.convert(results, MapFenceDevices.class);
    }

    @Override
    public List<MapFenceDevices> findAll() {
        return MapstructUtils.convert(MapFenceDevicesRepository.findAll(), MapFenceDevices.class);
    }
    private Predicate buildPredicate(MapFenceDevices data) {
        return PredicateBuilder.instance()
                .and(data.getId()!=null, () -> tbMapFenceDevices.id.eq(data.getId()))
                .and(data.getPid()!=null, () -> tbMapFenceDevices.pid.eq(data.getPid()))
                .and(data.getDeviceId()!=null,()->tbMapFenceDevices.deviceId.eq(data.getDeviceId()))
                .build();
    }

    public JPAQuery<MapFenceDevices> buildSelect(MapFenceDevices data){
        Predicate predicate = buildPredicate(data);
        return jpaQueryFactory.select(Projections.bean(MapFenceDevices.class,
                        tbMapFenceDevices.id,tbMapFenceDevices.pid,tbMapFenceDevices.remark,tbMapFenceDevices.uid,tbMapFenceDevices.createAt,tbMapFenceDevices.createDept,
                        tbMapFenceDevices.tenantId,tbMapFenceDevices.updateAt,tbMapFenceDevices.updateBy,tbMapFenceDevices.deviceId,tbMapFenceDevices.amapTid,
                        Expressions.as(tbProduct.name, Expressions.stringPath("productName")),tbProduct.productKey,tbMapFenceDevices.gfid,
                        tbDeviceInfo.deviceName
                ))
                .from(tbMapFenceDevices)
                .leftJoin(tbDeviceInfo).on(tbDeviceInfo.id.eq(tbMapFenceDevices.deviceId))
                .leftJoin(tbProduct).on(tbProduct.productKey.eq(tbDeviceInfo.productKey))
                .where(predicate);
    }

    public List<MapFenceDevices> findAllByCondition(MapFenceDevices query) {
        List<MapFenceDevices> results = buildSelect(query).fetch();
        return results;

    }

    public Paging<MapFenceDevices> findAllByConditions(PageRequest<MapFenceDevices> pageRequest) {
        MapFenceDevices data = pageRequest.getData();
        QueryResults<MapFenceDevices> results = buildSelect(data).limit(pageRequest.getPageSize()).offset(pageRequest.getOffset()).fetchResults();
        return new Paging<>(results.getTotal(), results.getResults());

    }
}
